﻿using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;

namespace TokenManagementAppMVC.Services
{
    /// <summary>
    /// JWT Token 验证服务
    /// 适用于 .NET Framework 4.5.2 环境
    /// 使用 v4.0.0 版本的 System.IdentityModel.Tokens.Jwt
    /// </summary>
    public class JwtTokenValidator
    {
        public static ClaimsPrincipal ValidateToken(string token, string secretKey, string issuer, string audience)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = System.Text.Encoding.UTF8.GetBytes(secretKey);

            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = true,
                ValidIssuer = issuer,
                ValidateAudience = true,
                ValidAudience = audience,
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero // 严格验证过期时间
            };

            try
            {
                return tokenHandler.ValidateToken(token, validationParameters, out _);
            }
            catch (SecurityTokenException ex)
            {
                // Token验证失败
                Console.WriteLine($"Token validation failed: {ex.Message}");
                return null;
            }
        }
    }
}